#include "../../server.hpp"

std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
void ConnectionDestroy(const PtrConnection &conn){
    _conns.erase(conn->Id());
}

void OnMessage(const PtrConnection &conn, Buffer *buf){
    DEBUG_LOG("%s", buf->read_pos());
    buf->move_reader(buf->readable_size());
    std::string str = "hello cli";
    conn->Send(str.c_str(), str.size());
}

void OnConnected(const PtrConnection &conn){
    DEBUG_LOG("New Connection: %p", conn.get());
}

void Acceptor(EventLoop *loop, Channel *lis_channel){
    int fd = lis_channel->Fd();
    int newfd = ::accept(fd, nullptr, nullptr);
    DEBUG_LOG("accepted: %d", newfd);
    if(newfd < 0) return;

    conn_id++;
    PtrConnection conn(new Connection(loop, conn_id, newfd));
    
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetSvrClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();
    
    _conns.insert(std::make_pair(conn_id, conn));
}

int main(){
    EventLoop loop;
    Socket lis_sock;
    bool ret = lis_sock.CreateServer(8500);

    Channel channel(&loop, lis_sock.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel));
    channel.EnableRead();
    while(true){
        loop.Start();
        sleep(1);
    }
    lis_sock.Close();
    return 0;
}